package main

import (
	"fmt"
	"os"
	"strconv"
	"time"
)

const lineTxt = " - c++/go/cangjie 测试文本写入文件的速度/性能，需要高频写入日志的场景对写文件性能关注会比较高 - 2024 ++++ c++/go/cangjie 测试文本写入文件的速度/性能，需要高频写入日志的场景对写文件性能关注会比较高 - 2024"

func main() {

	startTime := time.Now()
	var totalWriteSize int64 = 0
	for i := 0; i < 10; i++ {
		totalWriteSize = stringWriteToFile()
	}
	useMs := time.Now().Sub(startTime).Milliseconds() / 10
	fmt.Printf("文件写入完毕,文件总大小：%d - ，平均单次耗时(ms):%d\n", totalWriteSize, useMs)

}

func stringWriteToFile() int64 {
	filePath := "D:/写文件/log_go_no_buffer.txt"
	rows := 1000000 // 写入100万行文本，模拟写入日志场景
	file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0777)
	if err == nil {
		for i := 1; i <= rows; i++ {
			_, _ = file.WriteString(strconv.Itoa(i) + lineTxt + "\n")
		}
		if fileInfo, err := file.Stat(); err == nil {
			_ = file.Close()
			return fileInfo.Size()
		}
	} else {
		fmt.Printf("创建文件出错：%+v\n", err.Error())
	}
	return 0
}
